# import socketserver
import struct
import json
import ssl
import newsocket
import filter
import makeRedis


def due(data):
    int_size = struct.calcsize("I")
    (i,), data = struct.unpack("I", data[:int_size]), data[int_size:]
    # print(data)
    k = data.decode()
    # print(k)
    try:
        t = json.loads(k)
    except Exception:
        return 0
    return t


def dls(socket):
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    # 加载服务器所用证书和私钥
    context.load_cert_chain('/home/a/ou/key/server.crt', '/home/a/ou/key/server.key')
    request = context.wrap_socket(socket, server_side=False)
    return request


def due_data(data):
    if data['type'] == 'tcp':
        filter.tcp(data)
    if data['type'] == 'dns':
        filter.dns(data)
    if data['type'] == 'execve':
        filter.exe(data)
    if data['type'] == 'keep_alive':
        print(data['time'])
        filter.getcron(data['cron'])


class MyTCPHandler(newsocket.BaseRequestHandler):
    def handle(self):
        try:
            while True:
                self.data = self.request.recv(1024)
                # print("{} send:".format(self.client_address), self.data)
                data = due(self.data)
                if data:
                    due_data(data)
                if not self.data:
                    print("connection lost")
                    break
                self.request.sendall(self.data.upper())
        except Exception as e:
            print(e)
        finally:
            self.request.close()

    def setup(self):
        print("before handle,连接建立：", self.client_address)

    def finish(self):
        print("finish run  after handle")


host = "127.0.0.1"
port = 8887

server = newsocket.ThreadingTCPServer((host, port), MyTCPHandler)  # 多线程版
server.serve_forever()
